<?php
/**
 * admin service file Created by PhpStorm.
 * User: yang
 * Date: 2020/06/15
 */

namespace App\Http\Service\Web;

use Common\Repository\ForumRepository;
use Common\Repository\ForumCommentRepository;
use Common\Repository\ForumZanRepository;

class ForumService
{
    /**
     * 获取列表
     * @param array $get_data
     * @return array
     */
    public function getList($get_data = [])
    {
        try {
            if ($get_data['sort'] == 'newest') {
                $arr_option['order'] = ['key' => 'created_at', 'value' => 'desc'];
            } elseif ($get_data['sort'] == 'host') {
                $arr_option['order'] = ['key' => 'comment', 'value' => 'desc'];
            } else {
                $arr_option['order'] = ['key' => 'is_top', 'value' => 'desc'];
            }

            $arr_option['limit'] = 15;
            $arr_option['where'] = $get_data['where'];
            $arr_option['with'] = ['get_user', 'get_type'];
            $arr_option['withCount'] = ['get_comment'];

            $user = web_user_info();
            if ($user) {
                $arr_option['orWhere']['user_id'] = $user['id'];
                if (!empty($get_data['where']['tag'])) {
                    $arr_option['orWhere']['tag'] = $get_data['where']['tag'];
                }
                if (!empty($get_data['where']['type_id'])) {
                    $arr_option['orWhere']['type_id'] = $get_data['where']['type_id'];
                }
            }
            $result = ForumRepository::extendGetList($arr_option);
            $result['user'] = $user;

            return $result;
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 最近热议
     * @return array
     */
    public function hostList()
    {
        try {
            $arr_option['limit'] = 10;
            $arr_option['where'] = ['status' => 0];
            $arr_option['withCount'] = ['get_comment'];
            $arr_option['order'] = ['key' => 'get_comment_count', 'value' => 'desc'];
            $arr_option['field'] = ['id', 'title'];
            $list = ForumRepository::getList($arr_option);

            return $list['data'];
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 添加操作
     * @param array $post_data
     * @return array
     */
    public function insert($post_data = [])
    {
        try {
            $post_data['content'] = htmlentities($post_data['content'], ENT_COMPAT);
            $result = ForumRepository::addOne($post_data);

            if ($result) {
                return hello_success('发布成功！', ['back' => '/forumDetail/' . $result['id']]);
            }

            return hello_error('发布失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 编辑视图
     *
     * @param int $id
     * @return array
     */
    public function edit(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            $arr_option['with'] = ['get_user', 'get_type'];
            $arr_option['withCount'] = ['get_comment'];
            $result = ForumRepository::findOne($id, $arr_option);

            if ($result) {
                return hello_success('获取成功！', $result);
            }

            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 详情
     * @param int $id
     * @return array
     */
    public function detail(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            $arr_option['with'] = ['get_user', 'get_type'];
            $arr_option['withCount'] = ['get_comment'];
            $result = ForumRepository::findOne($id, $arr_option);
            $result['user'] = web_user_info();

            if ($result) {
                ForumRepository::increaseNum($id);
                return hello_success('获取成功！', $result);
            }

            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 编辑操作
     *
     * @param array $post_data
     * @return array
     */
    public function update($post_data = [])
    {
        try {
            $post_data['content'] = htmlentities($post_data['content'], ENT_COMPAT);
            $result = ForumRepository::editOne($post_data);

            if ($result) {
                return hello_success('编辑成功！', ['back' => '/forumDetail/' . $post_data['id']]);
            }

            return hello_error('编辑失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 删除操作
     *
     * @param int $id
     * @return array
     */
    public function delete(int $id)
    {
        try {
            if ($id == 0) {
                error_prompt('参数错误');
            }
            $user = web_user_info();
            $where = ['id' => $id, 'user_id' => $user['id']];
            $result = ForumRepository::deleteByWhere($where);

            if ($result) {
                return hello_success('删除成功！', $result);
            }

            return hello_error('删除失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 评论/回复
     * @param array $post_data
     * @return array
     */
    public function reply($post_data = [])
    {
        try {
            $user = web_user_info();
            $post_data['user_id'] = $user['id'];
            $post_data['content'] = htmlentities($post_data['content'], ENT_COMPAT);
            $result = ForumCommentRepository::addOne($post_data);

            $cate = $post_data['type'] == '1' ? '评论' : '回复';
            if ($result) {
                $res = self::commentList(['id' => $post_data['forum_id']]);
                return hello_success($cate . '成功！', $res['data']);
            }

            return hello_error($cate . '失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 获取评论列表
     * @param array $get_data
     * @return array
     */
    public function commentList($get_data = [])
    {
        try {
            $forum_id = (int)$get_data['id'];
            if ($forum_id == 0) {
                error_prompt('参数错误');
            }

            $arr_option['field'] = ['id', 'user_id'];
            $arr_option['with'] = ['get_comment' => function ($comment) {
                $comment->with(['get_comm_zan'])
                    ->orderBy('is_adopt', 'desc')
                    ->orderBy('updated_at', 'desc')
                    ->paginate(10);//默认展示10条评论
            }];

            $result = ForumRepository::findOne($forum_id, $arr_option);
            $list = self::commentInfo($result);

            if ($list) {
                return hello_success('获取成功！', $list);
            }
            return hello_error('获取失败！');
        } catch (\Exception $exception) {
            return hello_error('失败！', $exception->getMessage());
        }
    }

    /**
     * 列表数据处理
     * @param array $data
     * @return string
     */
    public function commentInfo($data = [])
    {
        $user = web_user_info();
        if ($user) {
            $uid = $user['id'];
        }else{
            $ip = preg_replace('/[^0-9]/', '', $_SERVER['REMOTE_ADDR']);
            $uid = (int)substr($ip,-6);
        }

        $html = '';
        foreach ($data['get_comment'] as $key => $value) {
            $rank = '';
            if ($value["get_user"]["rank"] > 0) {
                $rank = '<i class="iconfont icon-renzheng"></i><i class="layui-badge fly-badge-vip">VIP' . $value["get_user"]["rank"] . '</i>';
            }
            $isAuth = $data["user_id"] == $value["user_id"] ? "(楼主)" : "";

            $operate = '';
            if ($value["user_id"] == $user['id']) {
                $operate = '<!--<span type="edit">编辑</span>-->
                <span type="del" class="commentDel" data-id="' . $value["id"] . '">删除</span>';
            }

            $accept = '';
            if ($data["user_id"] == $user['id']) {
                if ($value['is_adopt'] == 1) {
                    $accept = '<span class="jieda-accept commentAccept" data-id="' . $value["id"] . '" type="no">取消采纳</span>';
                } else {
                    $accept = '<span class="jieda-accept commentAccept" data-id="' . $value["id"] . '" type="ok">采纳</span>';
                }
            }

            $is_adopt = $value['is_adopt'] == 1 ? '<i class="iconfont icon-caina" title="最佳答案"></i>' : '';
            $commZan = array_column($value['get_comm_zan'], 'user_id');
            $zanok = in_array($uid, $commZan) ? 'zanok' : 'zanno';

            $html .= '<li data-id="111" class="jieda-daan">
            <div class="detail-about detail-about-reply">
              <a class="fly-avatar" href="/userHome?id=' . $value["user_id"] . '">
                <img src="' . $value["get_user"]["head_img"]["url"] . '">
              </a>
              <div class="fly-detail-user">
                <a href="/userHome?id=' . $value["user_id"] . '" class="fly-link">
                  <cite>' . $value["get_user"]["name"] . '</cite>
                  ' . $rank . '
                </a>
                <span>' . $isAuth . '</span>
              </div>
              <div class="detail-hits">
                <span>' . friendly_date($value["created_at"]) . '</span>
              </div>
              ' . $is_adopt . '
            </div>
            <div class="detail-body jieda-body photos">' . $value["content"] . '</div>
            <div class="jieda-reply">
              <span class="jieda-zan commentZan ' . $zanok . '" data-id="' . $value["id"] . '" type="' . $zanok . '">
                <i class="iconfont icon-zan"></i>
                <em>' . count($commZan) . '</em>
              </span>
              <a href="#comment" class="reply" data-pid="' . $value["id"] . '">
                <span type="reply"><i class="iconfont icon-svgmoban53"></i>回复</span>
              </a>
              <div class="jieda-admin">' . $operate . $accept . '</div>
            </div>
          </li>';
        }

        return $html ? $html : '<li class="fly-none">消灭零回复</li>';
    }

    /**
     * $data[type](1点赞，2采纳，3删除评论)
     * @param $data
     * @return array
     */
    public function operate($data = [])
    {
        try {
            if ($data['type'] == '1') {

                return self::commentZan($data);

            } elseif ($data['type'] == '2') {

                return self::commentAccept($data);

            } elseif ($data['type'] == '3') {

                return self::commentDel($data);

            } else {
                return hello_error('type参数错误！');
            }
        } catch (\Exception $exception) {
            return hello_error('失败', '', $exception->getMessage());
        }
    }

    /**
     * 点赞取消点赞
     * @param $data
     * @return array
     */
    public function commentZan($data)
    {
        $user = web_user_info();
        if ($user) {
            $uid = $user['id'];
        }else{
            $ip = preg_replace('/[^0-9]/', '', $_SERVER['REMOTE_ADDR']);
            $uid = (int)substr($ip,-6);
        }

        $map = ['forum_id' => $data['forum_id'], 'comment_id' => $data['comment_id'], 'user_id' => $uid, 'type' => 2];
        if ($data['zan'] == 'zanno') {
            $res = ForumZanRepository::addOne($map);
        } else {
            $res = ForumZanRepository::deleteByWhere($map, true);
        }
        if ($res) {
            return hello_success('成功！');
        }

        return hello_error('失败！');
    }


    /**
     * 是否采纳评论
     * @param $data
     * @return array
     */
    public function commentAccept($data)
    {
        $map = ['id' => (int)$data['comment_id'], 'forum_id' => (int)$data['forum_id']];
        if ($data['accept'] == 'no') {
            $updata = ['is_adopt' => 0];
        } else {
            $updata = ['is_adopt' => 1];
        }

        $result = ForumCommentRepository::editByWhere($map, $updata);

        if ($result) {
            return self::commentList(['id' => $data['forum_id']]);
        }

        return hello_error('设置失败！');
    }

    /**
     * 删除评论
     * @param $data
     * @return array
     */
    public function commentDel($data)
    {
        if (empty($data['id'])) {
            return hello_error('参数错误！');
        }
        $user = web_user_info();
        $map = ['id' => $data['id'], 'user_id' => $user['id']];
        $res = ForumCommentRepository::deleteByWhere($map);
        if ($res) {
            return hello_success('删除成功！');
        }
        return hello_error('失败！');
    }
}